import renders from './renders';
var jschardet = require("jschardet")

export async function readBuffer(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = loadEvent => resolve(loadEvent.target.result);
    reader.onerror = e => reject(e);
    reader.readAsArrayBuffer(file);
  });
}

export async function readDataURL(buffer) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = loadEvent => resolve(loadEvent.target.result);
    reader.onerror = e => reject(e);
    reader.readAsDataURL(new Blob([buffer]));
  });
}

export async function readText(buffer) {
  return new Promise((resolve, reject) => {
    const viewBuf = new Uint8Array(buffer);
    let str = "";
    for (var index in viewBuf) {
      str += String.fromCharCode(viewBuf[index]);
      if (index >= 1000) {
        //考虑到效率，只取前1000个用于判断字符集
        break;
      }
    }
    var codepage = jschardet.detect(str.substring(0, 1000)).encoding;
    console.log("🚀 ~ file: util.js:34 ~ 文本格式字符编码 ~ codepage:", codepage)
    const reader = new FileReader();
    reader.onload = loadEvent => resolve(loadEvent.target.result);
    reader.onerror = e => reject(e);
    reader.readAsText(new Blob([buffer]), codepage);
  });
}

export function getExtend(name) {
  const dot = name.lastIndexOf('.')
  return name.substr(dot + 1);
}

export async function render(buffer, type, target) {
  const handler = renders[type];
  if (handler) {
    return handler(buffer, target);
  }
  return renders.error(buffer, target, type);
}
